import router from './index';
import store from '../store';
import NProgress from 'nprogress'; // 进度条
import Cookies from 'js-cookie';
import 'nprogress/nprogress.css';
import {getToken} from "@/utils/auth";
import Vue from "vue"; // 进度条样式

const whiteList =['/login','/']

// 获取版本更新的jsonp回调函数
window.getVersion = (version) => {
    if (Cookies.get('app_version') !== version) {
        location.reload(); // 刷新页面
    }
    Cookies.set('app_version', version);
};
NProgress.configure({ showSpinner: false });
router.beforeEach((to, from, next) => {
    NProgress.start();
    // 发起jsonp：
    if (process.env.NODE_ENV === 'production') {
        // eslint-disable-next-line no-unreachable
        var versionScript = document.createElement('script');
        versionScript.src = location.origin + '/vue-material-admin/version.js?v=' + new Date().getTime();
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(versionScript, s);
    }

    // 给缓存页面增加刷新策略
    // 如果从需要缓存的页面跳转二级页面
    if (to.meta.keepAlive) {
        const toUrl = to.path.split('/');
        const fromUrl = from.path.split('/');
        if (toUrl[1] === fromUrl[1]) {
            to.meta.strategy = 'keep';
        } else {
            to.meta.strategy = 'refresh';
        }
    }


    const token = getToken()
    if (token){

        // store.dispatch('generateRoutes').then()

        if (to.path==="/login"){
            next({path:'/home'})
            NProgress.done()
        }else {
            if (store.getters.roles.length===0){  //为获取到角色信息
                store.dispatch('getUserInfo').then(res=>{
                    store.dispatch('generateRoutes').then(res=>{
                        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                    }).catch(err=>{
                        store.dispatch("logout").then(()=>{
                            new Vue().$breadstick.notify("系统繁忙，请稍后重试")
                            next('/login')
                        })
                    })
                }).catch(error=>{
                })
            }
            else {
                next()
            }
        }
    }
    else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }

});
router.afterEach(() => {
    NProgress.done(); // 结束Progress
});
